<template>
  <div class="mobile-register-container">
    <!-- 顶部导航 -->
    <van-nav-bar
        title="注册账号"
        left-text="返回"
        left-arrow
        @click-left="goBack"
        class="register-nav"
    />

    <!-- 注册表单 -->
    <div class="form-section">
      <van-form @submit="submitRegister" ref="registerFormRef" class="register-form" :show-error-message="false">
        <!-- 手机号 -->
        <div class="form-group">
          <div class="form-row">
            <span class="form-label">手机号:</span>
            <van-field
                v-model="registerForm.phone"
                name="phone"
                placeholder="请输入手机号码"
                :rules="[{ required: true, message: '请输入手机号' }]"
                clearable
                class="form-input"
                :class="{ 'input-error': errors.phone }"
                @blur="validateField('phone')"
                maxlength="11"
            >
              <template #left-icon>
                <van-icon name="phone-o" class="input-icon" />
              </template>
            </van-field>
          </div>
          <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>
        </div>

        <!-- 短信验证码 -->
        <div class="form-group">
          <div class="form-row">
            <span class="form-label">验证码:</span>
            <div class="sms-container">
              <van-field
                  v-model="registerForm.smsCode"
                  name="smsCode"
                  placeholder="请输入短信验证码"
                  :rules="[{ required: true, message: '请输入验证码' }]"
                  class="form-input sms-input"
                  :class="{ 'input-error': errors.smsCode }"
                  @blur="validateField('smsCode')"
                  maxlength="6"
              >
                <template #left-icon>
                  <van-icon name="comment-o" class="input-icon" />
                </template>
              </van-field>
              <van-button
                  size="small"
                  :disabled="smsCountdown > 0"
                  @click="sendSmsCode"
                  class="sms-btn"
              >
                {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '获取验证码' }}
              </van-button>
            </div>
          </div>
          <div v-if="errors.smsCode" class="error-message">{{ errors.smsCode }}</div>
        </div>

        <!-- 密码 -->
        <div class="form-group">
          <div class="form-row">
            <span class="form-label">密码:</span>
            <van-field
                v-model="registerForm.password"
                type="password"
                name="password"
                placeholder="请设置登录密码"
                :rules="[{ required: true, message: '请输入密码' }]"
                clearable
                class="form-input"
                :class="{ 'input-error': errors.password }"
                @blur="validateField('password')"
            >
              <template #left-icon>
                <van-icon name="lock" class="input-icon" />
              </template>
            </van-field>
          </div>
          <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
        </div>

        <!-- 确认密码 -->
        <div class="form-group">
          <div class="form-row">
            <span class="form-label">确认密码:</span>
            <van-field
                v-model="registerForm.confirmPassword"
                type="password"
                name="confirmPassword"
                placeholder="请再次输入密码"
                :rules="[{ required: true, message: '请确认密码' }]"
                clearable
                class="form-input"
                :class="{ 'input-error': errors.confirmPassword }"
                @blur="validateField('confirmPassword')"
            >
              <template #left-icon>
                <van-icon name="lock" class="input-icon" />
              </template>
            </van-field>
          </div>
          <div v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</div>
        </div>

        <!-- 用户协议 -->
        <div class="agreement-group">
          <van-checkbox v-model="agreeProtocol" shape="square" class="agreement-checkbox">
            我已阅读并同意
          </van-checkbox>
          <span class="protocol-link" @click="showProtocol">《用户协议》</span>
          和
          <span class="protocol-link" @click="showPrivacy">《隐私政策》</span>
        </div>
        <div v-if="errors.agreeProtocol" class="error-message agreement-error">{{ errors.agreeProtocol }}</div>

        <!-- 注册按钮 -->
        <div class="register-btn-wrapper">
          <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
              :disabled="loading"
              loading-text="注册中..."
              class="register-btn"
          >
            <span v-if="!loading">注 册</span>
          </van-button>
        </div>
      </van-form>

      <!-- 已有账号 -->
      <div class="login-link">
        <span>已有账号？</span>
        <span class="link-text" @click="goToLogin">立即登录</span>
      </div>
    </div>

    <!-- 协议弹窗 -->
    <van-dialog
        v-model:show="showProtocolDialog"
        title="用户协议"
        show-cancel-button
        confirm-button-text="同意"
        class="protocol-dialog"
    >
      <div class="protocol-content">
        <h3>宠物世家用户协议</h3>
        <p>欢迎使用宠物世家服务！请仔细阅读以下协议内容...</p>
        <!-- 这里可以放详细的协议内容 -->
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { showSuccessToast, showFailToast } from 'vant'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const registerFormRef = ref()

// 注册表单数据
const registerForm = reactive({
  phone: '',
  smsCode: '',
  password: '',
  confirmPassword: ''
})

// 错误信息
const errors = reactive({
  phone: '',
  smsCode: '',
  password: '',
  confirmPassword: '',
  agreeProtocol: ''
})

// 短信验证码相关
const smsCountdown = ref(0)
const agreeProtocol = ref(false)
const showProtocolDialog = ref(false)

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/mobile/login')
}

// 验证单个字段
const validateField = (fieldName) => {
  const value = registerForm[fieldName]

  switch (fieldName) {
    case 'phone':
      errors.phone = value ? (/^1[3-9]\d{9}$/.test(value) ? '' : '手机号格式不正确') : '手机号不能为空'
      break
    case 'smsCode':
      errors.smsCode = value ? (/^\d{6}$/.test(value) ? '' : '验证码必须是6位数字') : '验证码不能为空'
      break
    case 'password':
      errors.password = value ? (value.length >= 6 ? '' : '密码至少6位') : '密码不能为空'
      break
    case 'confirmPassword':
      errors.confirmPassword = value ? (value === registerForm.password ? '' : '两次密码不一致') : '请确认密码'
      break
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!registerForm.phone) {
    showFailToast('请输入手机号')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(registerForm.phone)) {
    showFailToast('手机号格式不正确')
    return
  }

  try {
    // 这里调用发送短信的API
    // await sendSmsApi(registerForm.phone)
    showSuccessToast('验证码已发送')

    // 开始倒计时
    smsCountdown.value = 180
    const timer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    showFailToast('发送失败，请重试')
  }
}

// 显示用户协议
const showProtocol = () => {
  showProtocolDialog.value = true
}

// 显示隐私政策
const showPrivacy = () => {
  showFailToast('隐私政策功能开发中')
}

// 提交注册
const submitRegister = async () => {
  // 清除旧错误
  Object.keys(errors).forEach(key => errors[key] = '')

  // 验证所有字段
  validateField('phone')
  validateField('smsCode')
  validateField('password')
  validateField('confirmPassword')

  // 验证协议
  if (!agreeProtocol.value) {
    errors.agreeProtocol = '请阅读并同意用户协议'
  }

  // 检查是否有错误
  const hasErrors = Object.values(errors).some(error => error)
  if (hasErrors) {
    showFailToast('请完善表单信息')
    return
  }

  try {
    loading.value = true

    // 这里调用注册API
    // const resp = await registerApi(registerForm)

    // 模拟注册成功
    setTimeout(() => {
      showSuccessToast('注册成功')
      router.push('/mobile/login')
    }, 1000)

  } catch (error) {
    showFailToast(error.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.mobile-register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.register-nav {
  background: transparent;
  :deep(.van-nav-bar__content) {
    background: transparent;
  }
  :deep(.van-nav-bar__title),
  :deep(.van-nav-bar__text) {
    color: white;
  }
  :deep(.van-icon) {
    color: white;
  }
}

.form-section {
  padding: 20px;
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 4px;
}

.form-label {
  font-size: 16px;
  font-weight: 600;
  color: white;
  min-width: 70px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 透明输入框 */
.form-input {
  flex: 1;
  background: transparent !important;
  border: 2px solid rgba(255, 255, 255, 0.5);
  border-radius: 10px;
  transition: all 0.3s ease;
}

.form-input :deep(.van-field__body) {
  background: transparent !important;
  padding: 12px 0;
}

.form-input :deep(.van-field__control) {
  color: white;
  font-size: 16px;
  background: transparent !important;
}

.form-input :deep(.van-field__control::placeholder) {
  color: rgba(255, 255, 255, 0.7);
}

.form-input.input-error {
  border-color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1) !important;
}

.form-input.input-error :deep(.van-field__control) {
  color: #ff4d4f;
}

.input-icon {
  color: rgba(255, 255, 255, 0.8);
  margin-right: 8px;
}

/* 短信验证码容器 */
.sms-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}

.sms-input {
  flex: 1;
}

.sms-btn {
  flex-shrink: 0;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  border-radius: 6px;
  height: 36px;
}

.sms-btn:disabled {
  opacity: 0.6;
}

/* 错误消息样式 */
.error-message {
  color: #ff4d4f;
  font-size: 13px;
  margin-top: 6px;
  padding: 0 12px;
  text-align: right;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.agreement-error {
  text-align: center;
}

/* 用户协议 */
.agreement-group {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  margin: 25px 0 10px 0;
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
}

.agreement-checkbox {
  :deep(.van-checkbox__icon) {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
  }
  :deep(.van-checkbox__label) {
    color: rgba(255, 255, 255, 0.9);
  }
}

.protocol-link {
  color: #ffd700;
  cursor: pointer;
  text-decoration: underline;
}

.protocol-link:hover {
  color: #ffed4e;
}

/* 注册按钮 */
.register-btn-wrapper {
  margin: 20px 0;
  width: 100%;
}

.register-btn {
  height: 50px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  font-size: 18px;
  font-weight: 600;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  width: 100%;
}

.register-btn:active {
  transform: translateY(2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 登录链接 */
.login-link {
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
  margin-top: 20px;
}

.link-text {
  color: #ffd700;
  cursor: pointer;
  font-weight: 500;
  margin-left: 5px;
}

.link-text:hover {
  text-decoration: underline;
}

/* 协议弹窗 */
.protocol-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.protocol-content h3 {
  color: #333;
  margin-bottom: 15px;
}

.protocol-content p {
  color: #666;
  line-height: 1.6;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .form-section {
    padding: 15px;
  }

  .form-label {
    font-size: 15px;
    min-width: 65px;
  }

  .form-input :deep(.van-field__control) {
    font-size: 15px;
  }

  .register-btn {
    height: 48px;
    font-size: 16px;
  }

  .agreement-group {
    font-size: 13px;
  }
}

/* 移除van-field默认样式 */
:deep(.van-field__label),
:deep(.van-field__error-message) {
  display: none !important;
}

:deep(.van-cell-group) {
  background: transparent;
}
:deep(.van-cell-group::after) {
  display: none;
}

:deep(.van-field) {
  background: transparent !important;
}
</style>